//
//  BulletView.m
//  linktuIOS
//
//  Created by 章为 on 16/5/31.
//  Copyright © 2016年 张伟. All rights reserved.
//

#import "BulletView.h"
#import "UIButton+WebCache.h"
#import "POP.h"
#define mWidth [UIScreen mainScreen].bounds.size.width
#define mHeight [UIScreen mainScreen].bounds.size.height
#define mDuration   10
#define Padding  5
#define userAccessUrl  [NSString stringWithFormat:@"%@Zhibo/getViewerInfo", apihttp2]
@interface BulletView()
@property (weak, nonatomic) IBOutlet UIButton *IconButton;
@property (weak, nonatomic) IBOutlet UILabel *nameLable;
@property (weak, nonatomic) IBOutlet UILabel *messageLable;
@property(nonatomic,strong) KLCPopup *pop;

@property (weak, nonatomic) IBOutlet UIView *bgView;

@property (nonatomic,assign) CGFloat bulletViewW;
//@property (weak, nonatomic) IBOutlet UIView *bg1View;


@end
@implementation BulletView
-(void)awakeFromNib
{
    [super awakeFromNib];
    self.IconButton.layer.cornerRadius = 16.5;
    self.IconButton.layer.masksToBounds = YES;
    UIImage * img = [UIImage imageNamed:@"bulletBack"];
    self.bgView.layer.contents = (__bridge id _Nullable)(img.CGImage);
}


-(void)layoutSubviews
{
//    UIColor *colorOne = [UIColor redColor];
//    UIColor *colorTwo = [UIColor lightGrayColor];
//    
//    
//    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//    gradientLayer.colors = @[(__bridge id)colorOne.CGColor, (__bridge id)colorTwo.CGColor];
////        gradientLayer.locations = @[@0.5, @0.1, @0.4];
//    gradientLayer.startPoint = CGPointMake(0, 0);
//    gradientLayer.endPoint = CGPointMake(1.0, 0);
//    gradientLayer.frame = self.bgView.frame;
//    [self.bgView.layer insertSublayer:gradientLayer atIndex:0];

    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bgView.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopLeft cornerRadii:CGSizeMake(16.5, 16.5)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bgView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.bgView.layer.mask = maskLayer;
}


+(instancetype)bulletView
{
    NSBundle *bud = [NSBundle mainBundle];
    NSArray *arry = [bud loadNibNamed:NSStringFromClass(self) owner:nil options:nil];
    BulletView *view = arry.lastObject;
    view.frame = CGRectMake(0, 0, 164, 33);
    return view;
}

+(instancetype)bulletViewWithMessage:(LTMessage *)message
{
    NSBundle *bud = [NSBundle mainBundle];
    NSArray *arry = [bud loadNibNamed:NSStringFromClass(self) owner:nil options:nil];
    BulletView *view = arry.lastObject;
    view.frame = CGRectMake(0, 0, 164, 33);
    view.message = message;
    [view.IconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:message.since.avatar] forState:UIControlStateNormal placeholderImage:defaultImgae options:SDWebImageCacheMemoryOnly completed:nil];
    view.nameLable.text = message.since.name;
    LTMessageTextBody *body = (LTMessageTextBody *)message.body;
    view.messageLable.text = body.text;
    return view;
}

//
-(void)setMessage:(LTMessage *)message
{
    _message = message;
    [self.IconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:message.since.avatar] forState:UIControlStateNormal placeholderImage:defaultImgae options:SDWebImageCacheMemoryOnly completed:nil];
    self.nameLable.text = message.since.name;
     LTMessageTextBody *body = (LTMessageTextBody *)message.body;
    NSString *messageText = body.text;
   _bulletViewW = [messageText boundingRectWithSize:CGSizeMake(MAXFLOAT, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11]} context:nil].size.width;
    self.messageLable.text = messageText;
}


- (void)startAnimation {
    
    //根据定义的duration计算速度以及完全进入屏幕的时间
    CGFloat wholeWidth =_bulletViewW + mWidth + 43;
    
    CGFloat speed =  20; //   wholeWidth/mDuration;

    CGFloat dur = (_bulletViewW + 43)/speed;
    
    NSLog(@"bulletview---------%f",CGRectGetWidth(self.messageLable.frame));
    
    
    __block CGRect frame = self.frame;
    if (self.moveBlock) {
        //弹幕开始进入屏幕
        self.moveBlock(Start);
    }
    
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(dur * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //dur时间后弹幕完全进入屏幕
        if (self.moveBlock) {
            self.moveBlock(Enter);
        }
    });
    
    
//    POPSpringAnimation *anim = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
    
    POPBasicAnimation *anim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewFrame];
    
    CGRect fromvalue =  CGRectMake([UIScreen mainScreen].bounds.size.width, self.y, self.width, self.height);
    CGRect tovalue = CGRectMake(-wholeWidth, self.y,self.width, self.height);
    
    anim.fromValue = [NSValue valueWithCGRect:fromvalue];
    anim.toValue = [NSValue valueWithCGRect:tovalue];
    
    anim.duration = (wholeWidth + 43)/speed;
    
    anim.beginTime = CACurrentMediaTime();
    [anim setCompletionBlock:^(POPAnimation *anim, BOOL finsih) {
        if(finsih){
            
            if (self.moveBlock) {
                self.moveBlock(End);
            }
            [self removeFromSuperview];
            
        }
    }];
    [self pop_addAnimation:anim forKey:@"go"];
    
    //弹幕完全离开屏幕

//    [UIView animateWithDuration:mDuration delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
//        frame.origin.x = -CGRectGetWidth(frame);
//        self.frame = frame;
//    } completion:^(BOOL finished) {
//        if (self.moveBlock) {
//            self.moveBlock(End);
//        }
//        [self removeFromSuperview];
//    }];
}

- (IBAction)buttonClick:(UIButton *)sender {
    
    NSDictionary *dict = @{@"userid":self.message.since.userId};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"bulletviewClick" object:nil userInfo:dict];

}

- (void)stopAnimation {
    [self.layer removeAllAnimations];
    [self removeFromSuperview];
}





-(void)headButtonPressed:(UIView *)view
{
  self.pop = [KLCPopup popupWithContentView:view showType:KLCPopupShowTypeBounceInFromBottom dismissType:KLCPopupDismissTypeBounceOutToLeft maskType:KLCPopupMaskTypeDimmed dismissOnBackgroundTouch:YES dismissOnContentTouch:NO];
}



@end
